import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// 1. 创建一个axios实例
const service = axios.create({
  baseURL: 'https://heimahr.itheima.net/api',
  timeout: 5000
})

// 2. 配置请求拦截器
service.interceptors.request.use(
  config => {
    // 2.1 如果有token，则设置token
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 3. 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
